<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 搜索条件 -->
      <el-form-item label="分组名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['eye:stockGroup:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['eye:stockGroup:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格列表 -->
    <el-table id="tableDiv" :height="tableHeight" v-loading="loading" border :data="stockGroupList"
              :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="分组名称" align="center" prop="name">
        <template slot-scope="scope">
          <span v-if="scope.row.classStyle === '' || scope.row.classStyle === 'default'">{{ scope.row.name }}</span>
          <el-tag v-else :type="scope.row.classStyle === 'primary' ? '' : scope.row.classStyle">{{ scope.row.name }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="分组序号" align="center" prop="sortNum"/>
      <el-table-column label="操作" width="200" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-star-off" @click="setDefaultAddGroup(scope.row)">默认添加</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['eye:stockGroup:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['eye:stockGroup:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页-->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 新增修改弹窗组件-->
    <addOrUpdate ref="addOrUpdateDialog" :visible.sync="addOrUpdateVisible" @getList="getList"/>

  </div>
</template>

<script>
import { listStockGroup, delStockGroup, listStockGroupOption, batchUpdateStockMyGroup } from '../../../api/eye/stockGroup'
import AddOrUpdate from './addOrUpdate'
import Sortable from 'sortablejs'

export default {
  name: 'StockGroup',
  components: { AddOrUpdate },
  data() {
    return {
      tableHeight: 200,
      addOrUpdateVisible: false,
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 股票分组表格数据
      stockGroupList: [],
      // 弹出层标题
      title: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        name: null,
        sortNum: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  mounted() {
    this.getTableMaxHeight()
    this.initSortable()
  },
  created() {
    this.listStockGroupOption()
    this.getList()
  },
  methods: {
    //获取容器当前高度，重设表格的最大高度
    getTableMaxHeight() {
      this.$nextTick(function() {
        let t = document.querySelector('#tableDiv')
        console.log('统计 重置高度')
        if (t == null) return
        this.tableHeight = window.innerHeight - t.getBoundingClientRect().top - 75
      })
    },
    tableRowClassName({row, rowIndex}) {
      console.log(this.$constants.GROUP_ID)
      if(row.id === this.$constants.GROUP_ID){
        console.log('9999999999')
        return 'warning-row'
      }
    },
    initSortable() {
      //将el-table变为可拖拽的
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const t = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          /*  console.log(evt)
           console.log(evt.from)
           console.log(evt.to) */

          let dragBeforeArray = JSON.parse(JSON.stringify(t.stockGroupList))
          let dragBeforeSortNum = dragBeforeArray.map(item => item.sortNum)

          console.log('拖动前所有数据:')
          console.log(JSON.stringify(dragBeforeArray))
          console.log('拖动前顺序:')
          console.log(dragBeforeSortNum)

          let dragAfterArray = []
          console.log('拖动前下标:' + oldIndex)
          console.log('拖动后下标:' + newIndex)
          console.log(dragBeforeArray)
          dragBeforeArray.splice(
            newIndex,
            0,
            dragBeforeArray.splice(oldIndex, 1)[0]
          )

          dragAfterArray = JSON.parse(JSON.stringify(dragBeforeArray))
          console.log('拖动后所有数据:')
          console.log(dragAfterArray)

          t.stockGroupList = []
          t.$nextTick(function() {
            t.stockGroupList = dragAfterArray
          })

          let update = []
          for (let i = 0; i < dragAfterArray.length; i++) {
            dragAfterArray[i].sortNum = dragBeforeSortNum[i]
            update.push({ id: dragAfterArray[i].id, sortNum: dragBeforeSortNum[i] })
          }

          console.log('拖动更新数据:')
          console.log(JSON.stringify(update))

          batchUpdateStockMyGroup(update).then(res => {
            t.$modal.msgSuccess(res.msg)
            // t.getList()
          })

        },
        // 元素被选中
        onChoose: function(/**Event*/evt) {
          console.log('选中元素:')
          console.log(evt)
          evt.oldIndex  // element index within parent
        }

      })
    },
    /** 查询股票分组列表 */
    getList() {
      this.loading = true
      listStockGroup(this.queryParams).then(response => {
        this.stockGroupList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    listStockGroupOption() {
      listStockGroupOption().then(response => {
        response.data.forEach((item) => {
          let o = {}
          o.value = item.id
          o.label = item.name
          o.listClass = item.classStyle
          o.raw = {}
          this.options.push(o)
        })
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addOrUpdateVisible = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.addOrUpdateVisible = true
      this.$refs.addOrUpdateDialog.handleUpdate(row)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除？').then(function() {
        return delStockGroup(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 设置添加股票的默认分组 */
    setDefaultAddGroup(row) {
      this.$constants.GROUP_ID = row.id
      this.$modal.msgSuccess('成功设置添加股票的默认分组ID:' + this.$constants.GROUP_ID)
    }
  }
}
</script>


<style scoped>
.el-table .warning-row {
  background: red !important;
}
</style>
